<!--
 @description 日期时间选择域
 @fileName index.vue
 @author zengqiongying
 @created 2022/10/30 15:45:35
-->
<template>
  <div class="c-field-datetime">
    <Cell
      :title="hideTitle ? '' : title"
      :subTitle="subTitle"
      :modelValue="curDate"
      :placeholder="placeholder"
      :required="required"
      :right="right"
      :input-align="inputAlign"
      :border="border"
      :cell-class-name="cellClassName"
      :left-icon="iconPosition === 'left' ? 'calendar-o' : ''"
      :right-icon="iconPosition === 'right' ? 'calendar-o' : ''"
      is-input
      click-input
      readonly
      v-bind="$attrs"
      @right="handleClickDate"
      @clear="handleClickClear"
    />
    <PopDateTimePicker
      v-model="showDate"
      :title="title"
      :default-value="defaultDate"
      :min-date="curMinDate"
      :max-date="curMaxDate"
      :calendar-type="calendarType"
      :show-time="showTime"
      :clear="showClear"
      @change="onConfirmDate"
    />
  </div>
</template>

<script lang="ts">
  import { reactive, toRefs, defineComponent, computed, watch } from 'vue'
  import { parseTime } from '@/utils'
  import Cell from '../Cell/index.vue'
  import PopDateTimePicker from '../PopDateTimePicker/index.vue'

  interface anyObjectModle {
    [key: string]: any
  }
  export default defineComponent({
    name: 'FieldDateTime',
    components: { Cell, PopDateTimePicker },
    inheritAttrs: true,
    props: {
      title: {
        type: String,
        default: undefined
      },
      subTitle: {
        type: String,
        default: undefined
      },
      hideTitle: {
        type: Boolean,
        default: false
      },
      modelValue: {
        type: [String, Array],
        default: ''
      },
      required: {
        type: Boolean,
        default: false
      },
      placeholder: {
        type: String,
        default: ''
      },
      disabled: {
        type: Boolean,
        default: false
      },
      minDate: {
        type: Date,
        default: null
      },
      maxDate: {
        type: Date,
        default: null
      },
      type: {
        type: String,
        default: 'date' // 日期类型（date 单个日期，daterange 日期范围,datetime  日期时间，datetimerange 日期时间范围）
      }, // 日历选择类型：single表示选择单个日期，range 表示选择日期区间,multiple表示选择多个日期(暂不支持)
      defaultDate: {
        type: [String, Array],
        default: ''
      },
      clear: {
        // 是否显示清除按钮
        type: Boolean,
        default: false
      },
      right: {
        // 是否显示右侧箭头
        type: Boolean,
        default: true
      },
      inputAlign: {
        // 输入框对齐方式：left/ right
        type: String,
        default: 'right'
      },
      border: {
        // 是否有边框
        type: Boolean,
        default: true
      },
      cellClassName: {
        type: String,
        default: ''
      },
      iconPosition: {
        // 日历图标位置：left /right
        type: String,
        default: ''
      }
    },
    emits: ['update:modelValue'],
    setup(props, { emit }) {
      const datas = reactive<anyObjectModle>({
        curDate: '',
        showDate: false
      })
      const curMinDate = computed(() => {
        if (props.minDate) {
          return props.minDate
        }
        const date = new Date()
        const sDate = new Date().setFullYear(date.getFullYear() - 2)
        return new Date(sDate)
      })
      const curMaxDate = computed(() => {
        if (props.maxDate) {
          return props.maxDate
        }
        const date = new Date()
        const sDate = new Date().setMonth(date.getMonth() + 6)
        return new Date(sDate)
      })
      const showTime = computed(() => {
        return props.type === 'datetime' || props.type === 'datetimerange'
      })
      const calendarType = computed(() => {
        if (props.type === 'datetime' || props.type === 'date') {
          return 'single'
        }
        if (props.type === 'datetimerange' || props.type === 'daterange') {
          return 'range'
        }
        return 'single'
      })
      const showClear = computed(() => {
        if (!props.clear) return false
        if (props.modelValue instanceof Array) {
          return props.modelValue.length > 0
        }
        return !!props.modelValue
      })
      watch(
        () => props.modelValue,
        (val) => {
          if (val instanceof Array) {
            if (val.length > 0) {
              datas.curDate = val.length === 2 ? val.join(' ~ ') : val[0]
            } else {
              datas.curDate = ''
            }
          } else {
            datas.curDate = val
          }
        },
        {
          immediate: true
        }
      )
      const handleClickDate = () => {
        if (props.disabled) return
        datas.showDate = true
      }
      const handleClickClear = () => {
        datas.curDate = ''
      }
      const onConfirmDate = (date: any) => {
        if (props.type === 'daterange') {
          datas.curDate = `${parseTime(date[0], '{y}-{m}-{d}')}  ~  ${parseTime(date[1], '{y}-{m}-{d}')}`
        } else if (props.type === 'datetimerange') {
          datas.curDate = `${parseTime(date[0], '{y}-{m}-{d} {h}:{i}:{s}')}  ~  ${parseTime(
            date[1],
            '{y}-{m}-{d} {h}:{i}:{s}'
          )}`
        } else if (props.type === 'datetime') {
          datas.curDate = parseTime(date, '{y}-{m}-{d} {h}:{i}:{s}')
        } else {
          datas.curDate = parseTime(date, '{y}-{m}-{d}')
        }
        emit('update:modelValue', date)
        datas.showDate = false
      }

      return {
        ...toRefs(datas),
        curMinDate,
        curMaxDate,
        showTime,
        calendarType,
        showClear,
        handleClickDate,
        handleClickClear,
        onConfirmDate
      }
    }
  })
</script>
<style lang="less" scoped></style>
